import logging
import os
from pathlib import Path
from django.core.management.base import BaseCommand
from django.db import connection

logger = logging.getLogger('django')


class Command(BaseCommand):
    help = "初始化项目"

    def getSql(self, filename):
        abspath = Path(__file__).resolve().parent.parent.parent.parent.parent
        pwd = os.path.join(abspath, 'scripts', filename)
        with open(pwd, 'rb') as f:
            # content = f.read().decode('utf8')
            # content.split('\n\r')
            content = f.read().decode('utf-8')
            content.strip()
            new_content = content.split(';')
            # for item in new_content:
            #     logger.info(item)
            # print(content)
            return [item for item in new_content if item != '']

    def doSql(self, name, filename):

        sql_list = self.getSql(filename)
        #
        with connection.cursor() as cursor:
            for sql in sql_list:
                try:
                    cursor.execute(sql)
                except Exception as e:
                    logger.info(e)
            connection.commit()
        # cursor.execute("select * from user;")
        # result = cursor.fetchone()
        # logger.info(result)
        pass

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        self.stdout.write("数据初始化！！")
        init_data = [
            {"name": "菜单表", "filename": "menu.sql"},
        ]
        for data in init_data:
            self.stdout.write(f"#####{data['name']},开始初始化数据！！")
            try:
                self.doSql(data['name'], data['filename'])
                self.stdout.write(f"#####{data['name']},初始化数据完成！！")
            except Exception as e:
                self.stdout.write(f"!!!!!{data['name']},初始化数据失败！！")
                logger.info(e)
        self.stdout.write("全部数据完成初始化！！")
